package arithmetic.leetCode.yi;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: yilin
 * Date: 2019-08-09
 * Time: 16:46
 */
public class LinkListRotateRight {


    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }


    }

    public static void main(String[] args) {
        ListNode node = new ListNode(1);
        node.next = new ListNode(2);
        node.next.next = new ListNode(3);
        node.next.next.next = new ListNode(4);
        node.next.next.next.next = new ListNode(5);

        ListNode result = rotateRight(node, 2);
        while (result != null) {
            System.out.print(result.val);
            result = result.next;
        }
    }

    public static ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null) return head;

        //链表的长度
        int count = 1;
        ListNode cur = head;
        while (cur.next != null) {
            ++count;
            cur = cur.next;
        }

        //链表首尾相连
        cur.next = head;
        //移动的位数
        count = count - k % count;
        for (int i = 0; i < count; i++) {
            cur = cur.next;
        }

        ListNode newNode = cur.next;
        cur.next = null;
        return newNode;
    }
}
